package io.renren.modules.clearing.service.impl;

import cn.com.taiji.common.manager.net.http.binclient.ApiRequestException;
import cn.com.taiji.sdk.comm.LwClientHelper;
import cn.com.taiji.sdk.model.comm.protocol.cdts.passTransaction.ETCTransactionDownloadRequest;
import io.renren.common.utils.*;
import io.renren.commons.dynamic.datasource.annotation.DataSource;
import io.renren.modules.basedata.entity.XJException;
import io.renren.modules.clearing.dao.*;
import io.renren.modules.clearing.entity.*;
import io.renren.modules.clearing.service.ETCTransactionDownService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ETCTransactionDownServiceImpl implements ETCTransactionDownService {
    private Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    ConfigParaDicDao configParaDicDao;
    @Autowired
    DownVersionDicDao downVersionDicDao;
    @Autowired
    ZFKExitWasteDao zfkExitWasteDao;
    @Autowired
    DownErrorVersionDao downErrorVersionDao;
    @Autowired
    TblExitetctranslistDao tblExitEtcTransDao;
    @Override
    public String[] ETCTransactionDown() throws Exception {
        String msg="";
        String version=null;
        String[] versions=null;
        log.info("开始检查控制参数");
        //检查控制参数是否下载 tbl_configparadic
        int control = configParaDicDao.checkContolParam(Constants.CONTROL_ETCAUDOWN_PARAM);
      //  int control=(Integer) sqlMapClient.queryForObject("Base_ORACLE.checkContolParam", Constants.CONTROL_ETCTRANSACTIONDOWN_PARAM);
        if(control==1){
            //获取要需下载的版本号
            version = downVersionDicDao.getVersion(Constants.DOWNLOAD_TYPE_ETCACCOUNTTRADEDOWNLOAD);
            if(version!=null ){
                //判断有多少版本号要处理
                versions= TypeTransUtil.checkVersion(version, Constants.DOWNLOAD_FILE_15M);

            }else{
                msg="版本字典表无该参数配置";
                log.info(msg);
            }

        }else{
            msg="接口暂停，任务退出";
            log.info(msg);
        }

        return versions;
    }

    @Override
    public boolean DownloadFile(String version, int type) throws Exception {
        boolean flag=false;
        ETCTransactionDownloadRequest request = new ETCTransactionDownloadRequest();
        request.setVersion(version);
        request.setReqSender(Config.issuerId);
        log.info("开始执行版本:"+version);
        String path=";文件路径:";
        try {
            File file = LwClientHelper.downLoad(request, Constants.DOWNLOAD_PATH_ETCTRANSACTION);//正式
            //File file = new File("E:\\download\\ETCTransaction\\CDPS_ETCTS_TD_650101_201811201844.zip");//测试
            log.info("ETC交易下载成功，下载文件为："+file.getAbsolutePath());
            path=path+file.getAbsolutePath();
            //解压文件
            String filedir=file.getAbsolutePath().substring(0, file.getAbsolutePath().lastIndexOf("."));
            ZipUncompress.unZip(file.getAbsolutePath(),filedir);
            //获取解压目录下的所有文件
            List<File> filelist = FileTool.getFileList(filedir);
            log.info("解压文件共"+filelist.size()+"个json文件");
            if(filelist.size()==0){
                log.info("空包文件，退出任务");
                return true;
            }
            //循环解析所有文件入库
            String fileName=null;
            Date nowTime= new Date();
            for (File f :filelist) {
                fileName = f.getName();
                log.info("开始解析"+fileName+"文件");
                String filejsonstr=	FileTool.getjsonStr(filedir+"\\"+fileName);
                //log.info(fileName+"文件内容："+filejsonstr);
                //将json串转对象
                etcDown etc= (etcDown) FileTool.parseJsonToObj(filejsonstr, etcDown.class);
                if(etc!=null){
                    //校验数据
                    if(etc.getTransaction()==null){
                        log.info("交易包："+etc.getMessageId()+"服务方："+etc.getTollProvinceId()+"数据格式异常");
                        throw new XJException(Constants.DOWNLOAD_TYPE_ETCTRANSACTION, version, "ETC交易下载请求失败交易包："+etc.getMessageId()+"服务方："+etc.getTollProvinceId()+"数据格式异常,无明细数据"+path, 4);
                    }
                    //交易包号的唯一性
                    Integer count=null;
                    Map map = new HashMap();
                    map.put("messageID", etc.getMessageId());
                    map.put("userID", etc.getTollProvinceId());
                    count = zfkExitWasteDao.checkMessageIDByIssueID(map);
                    if(count!=null&&count>0){
                        log.info("交易包："+etc.getMessageId()+"服务方："+etc.getTollProvinceId()+"已存在");
                        //添加版本异常表
                        throw new XJException(Constants.DOWNLOAD_TYPE_ETCTRANSACTION, version, "ETC交易下载请求响应失败交易包："+etc.getMessageId()+"服务方："+etc.getTollProvinceId()+"原始交易已存在，交易包重复"+path+"--"+fileName, 4);

                    }
                    //交易文件中的总计和明细是否一致条数与汇总是否一致

                    if(etc.getCount()!=etc.getTransaction().size()){
                        log.info("总流量："+etc.getCount()+"与流水明细条数："+etc.getTransaction().size()+"不一致");
                        //添加版本异常表
                        throw new XJException(Constants.DOWNLOAD_TYPE_ETCTRANSACTION, version, "ETC交易下载请求响应失败交易包："+etc.getMessageId()+"总流量："+etc.getCount()+"与流水明细条数："+etc.getTransaction().size()+"不一致"+path+"--"+fileName, 4);
                    }
                    //交易文件中的总计和明细是否一致总金额与汇总是否一致
                    int amount=0;
                    for (int i = 0; i < etc.getTransaction().size(); i++) {
                        amount+=etc.getTransaction().get(i).getFee();
                    }
                    if(amount!=etc.getAmount()){
                        log.info("总金额："+etc.getAmount()+"与流水合计金额："+amount+"不一致");
                        //添加版本异常表
                        throw new XJException(Constants.DOWNLOAD_TYPE_ETCTRANSACTION, version, "ETC交易下载请求响应失败交易包："+etc.getMessageId()+"总金额："+etc.getAmount()+"与流水合计金额："+amount+"不一致"+path+"--"+fileName, 4);

                    }
                    //保存zfk数据

                    for (int i = 0; i < etc.getTransaction().size(); i++) {
                        //tbl_ZFKExitWaste zfk =fullZfkWaste(etc.getTransaction().get(i),etc);
                        //sqlMapClient.insert("ZfkExitW_ORACLE.addZfkExitWaste",zfk);
                        //写入mysql
                        TblExitetctranslistEntity tblExitetctranslist = new TblExitetctranslistEntity();
                        tblExitetctranslist.setExitStationId(etc.getTransaction().get(i).getExTollStationName());
                        tblExitetctranslist.setRecId(etc.getTransaction().get(i).getId());
                        tblExitetctranslist.setUserCardId(etc.getTransaction().get(i).getCardId());
                        tblExitetctranslist.setTerminalTransNo(etc.getTransaction().get(i).getTerminalTransNo());
                        tblExitetctranslist.setObuId(etc.getTransaction().get(i).getObuid());
                        tblExitetctranslist.setEntryVehicleId(etc.getTransaction().get(i).getEnVehicleId());
                        tblExitetctranslist.setEntryRoadnetId("");
                        tblExitetctranslist.setEntryStationId(etc.getTransaction().get(i).getEnTollStationName());
                        tblExitetctranslist.setEntryLaneId(etc.getTransaction().get(i).getEnTollLaneId());
                        tblExitetctranslist.setEntryVehicleType(etc.getTransaction().get(i).getEnVehicleType());
                        tblExitetctranslist.setExitVehicleId(etc.getTransaction().get(i).getExVehicleId());
                        tblExitetctranslist.setIdentifyVehicleId(etc.getTransaction().get(i).getIdentifyVehicleId());
                        tblExitetctranslist.setExitRoadnetId("");
                        tblExitetctranslist.setExitLaneId("");
                        tblExitetctranslist.setExitVehicleType(etc.getTransaction().get(i).getExVehicleType());
                        tblExitetctranslist.setIdentifyVehiclePic("");
                        tblExitetctranslist.setPreBalance(etc.getTransaction().get(i).getPreBalance().intValue());
                        tblExitetctranslist.setFee(etc.getTransaction().get(i).getFee().intValue());
                        tblExitetctranslist.setAfterBalance(etc.getTransaction().get(i).getPostBalance().intValue());
                        tblExitetctranslist.setWeight(etc.getTransaction().get(i).getWeight());
                        tblExitetctranslist.setTac(etc.getTransaction().get(i).getTac());
                        tblExitetctranslist.setTransType(etc.getTransaction().get(i).getTransType());
                        tblExitetctranslist.setIdentification(0000);
                        tblExitetctranslist.setTerminalNo(etc.getTransaction().get(i).getTerminalNo());
                        tblExitetctranslist.setTallyFlag(0000);
                        tblExitetctranslist.setDetails("");
                        tblExitetctranslist.setSpare1(0000);
                        tblExitetctranslist.setSpare2(0000);
                        tblExitetctranslist.setSpare3("0000");
                        tblExitetctranslist.setSpare4("0000");
                        save(tblExitetctranslist);

                        }

                }else{
                    log.info("解析"+fileName+"文件转换对象失败");
                    //添加版本异常表
                    throw new XJException(Constants.DOWNLOAD_TYPE_ETCTRANSACTION, version, "ETC交易下载请求响应失败解析"+fileName+"文件转换对象失败"+path, 4);

                }
                log.info("结束解析"+fileName+"文件");
                //删除文件
                f.delete();

            }
            if(type==1){
                addDownErrorVersion(version,Constants.DOWNLOAD_TYPE_ETCTRANSACTION, "ETC交易下载请求响成功文件："+file.getAbsolutePath(), 0);
                //修改下载版本号
                version=TypeTransUtil.getNextVersion(version, Constants.DOWNLOAD_FILE_15M);
                Map map2 = new HashMap<>();
                map2.put("version", version);
                map2.put("MsgType", Constants.DOWNLOAD_TYPE_ETCTRANSACTION);
                downVersionDicDao.editVersion(map2);
            }


            //删除文件夹
            File F = new  File(filedir);
            F.delete();
            flag=true;
        } catch (IOException e) {
            // TODO: handle exception
            log.info("ETC交易下载请求响应失败,版本号："+version+":"+e.getMessage());
            throw new Exception(new XJException(Constants.DOWNLOAD_TYPE_ETCTRANSACTION, version, "ETC交易下载请求响应失败IO异常,版本号："+version+path+":"+e.getMessage(), 1));
        } catch (ApiRequestException apie) {
            //TODO 系统自定义异常处理，各省补全
            apie.printStackTrace();
            if(apie.getErrCode()==Constants.EMPTYDATACODE){
                log.info("ETC交易下载请求无数据711,版本号："+version+":正常退出");
                if(type==1){
                    addDownErrorVersion(version,Constants.DOWNLOAD_TYPE_ETCTRANSACTION, "ETC交易下载请求响成功无数据", 0);
                    //修改下载版本号
                    version=TypeTransUtil.getNextVersion(version, Constants.DOWNLOAD_FILE_15M);
                    Map map2 = new HashMap<>();
                    map2.put("version", version);
                    map2.put("MsgType", Constants.DOWNLOAD_TYPE_ETCTRANSACTION);
                    downVersionDicDao.editVersion(map2);
                }
                flag=true;
            }else{
                log.error("ETC交易下载请求响应失败,版本号："+version+"错误码："+apie.getErrCode()+" 错误信息："+apie.getMessage());
                throw new Exception(new XJException(Constants.DOWNLOAD_TYPE_ETCTRANSACTION, version, "ETC交易下载请求响应失败错误码："+apie.getErrCode()+path+" 错误信息："+apie.getMessage(), apie.getErrCode()));
            }
        }catch (XJException e) {
            throw new Exception(e);
        }catch (SQLException e) {
            e.printStackTrace();
            String msg=TypeTransUtil.getErrorMessage(e.getMessage()) ;
            throw new Exception(new XJException(Constants.DOWNLOAD_TYPE_ETCTRANSACTION, version, "ETC交易下载请求响应失败:"+path+msg, 7));
        }catch (Exception e) {
            e.printStackTrace();
            //添加版本异常表
            String msg=TypeTransUtil.getErrorMessage(e.getMessage()) ;
            throw new Exception(new XJException(Constants.DOWNLOAD_TYPE_ETCTRANSACTION, version, "ETC交易下载请求响应失败:"+path+msg, 3));
        }

        return flag;
    }


    /**
     * 添加异常版本信息
     * @param version
     * @param reason
     * @param flag 0异常错误 ；1校验错误
     * @throws Exception
     */
    public void addDownErrorVersion(String version,int type,String reason,int flag)throws Exception{
        //添加版本异常表
        DownErrorVersion dv=TypeTransUtil.addDownErrorVersion(version,type, reason);
        dv.setFlag(flag);
        int count =downErrorVersionDao.selectDownErrorVersion(dv);
        if(count>0){
            downErrorVersionDao.editDownErrorVersion(dv);
        }else{
            downErrorVersionDao.addDownErrorVersion(dv);
        }
    }
    /**
     * 转换为zfk流水
     * @param etc
     * @return
     * @throws Exception
     */
    public tbl_ZFKExitWaste fullZfkWaste(etcDownTransaction Transaction, etcDown etc)throws Exception{
        tbl_ZFKExitWaste zfk = new tbl_ZFKExitWaste();
        //默认日期
        Date defaultDate = DateUtil.parseStringToDate("2000-01-01");
        String msg=etc.getMessageId()+"";
        msg=msg.length()>7?msg.substring(0, 7):msg;
        zfk.setExitTime(DateUtil.parseStringToDate2(Transaction.getExDate()+" "+Transaction.getExTime()));
        //zfk.setExitStationID(Integer.valueOf(msg));
        zfk.setExitStationID(TypeTransUtil.IDToStationID(Transaction.getId()));
        zfk.setExitLaneID(TypeTransUtil.transIDToExLaneID(Transaction.getId()));
        zfk.setExitWasteSN(TypeTransUtil.transIDToExitWasteSN(Transaction.getId()));
        zfk.setLaneType(4);
        zfk.setLaneAppVer(0);
        zfk.setLoginTime(defaultDate);
        zfk.setTriggerTime(defaultDate);
        zfk.setWorkDate(DateUtil.parseStringToDate(Transaction.getExDate()));
        zfk.setPayCardTranSN(Transaction.getTransNo().intValue());
        zfk.setKeyPressInfo(Transaction.getId());
        zfk.setPayCardBalance((double)Transaction.getPostBalance()/100);
        zfk.settAC(Long.parseLong(Transaction.getTac(), 16)+"");//需要将tac转10进制长整形
//			zfk.setpSAMID(Transaction.getTerminalNo());
        zfk.setpSAMID("0");
        zfk.setpSAMTradeSN(Integer.parseInt(Transaction.getTerminalTransNo(),16)+"");
        zfk.setvType(TypeTransUtil.getVtype(Transaction.getVehicleClass()));
        zfk.setvClass(Transaction.getExVehicleType());
        zfk.setvLP(Transaction.getExVehicleId().split("_")[0]);
        zfk.setTotalWeight(Transaction.getWeight());
        zfk.setDealStatus(Transaction.getSpecialType());
        zfk.setvCnt(1);
        zfk.setEntryStation(TypeTransUtil.EnLaneIDToStationID(Transaction.getEnTollLaneId()));

        zfk.setEntryLane(TypeTransUtil.transIDToExLaneID(Transaction.getEnTollLaneId()));
        zfk.setEntryTime(DateUtil.formatDateTime6(Transaction.getEnTime()));
        zfk.setEntryVClass(Transaction.getEnVehicleType());
        zfk.setEntryVLP(Transaction.getExVehicleId().split("_")[0]);
       // int cardType=TypeTransUtil.getCardTypeByCardID(Transaction.getCardId());
        //zfk.setStoreMoney(cardType==22?(double)Transaction.getFee()/100:0);
        //zfk.setTallyMoney(cardType==22?0:(double)Transaction.getFee()/100);
       // zfk.setStoreBalanceMoney((double)Transaction.getPostBalance()/100);
       // zfk.setOperType(cardType==22?0:1);
        zfk.setState(0);
//			zfk.setStatDesc(Transaction.getDescription());
        zfk.setStatDesc(Transaction.getEnTollStationName()+"|"+Transaction.getExTollStationName());
        zfk.setTransferDate(defaultDate);
        zfk.setTransferTime(defaultDate);
        zfk.setPrintTime(defaultDate);
        zfk.setUserID(Integer.valueOf(etc.getTollProvinceId()));
        zfk.setIssuerID(Double.valueOf(etc.getIssuerId().substring(0,2)));
        zfk.setCardNetID(TypeTransUtil.issueIDTonetID(etc.getIssuerId()));
        zfk.setPayCardID2(Transaction.getCardId().substring(4,20));
        zfk.setTerminalId(Transaction.getTerminalNo());
        zfk.setUpLoadTime(new Date());
        zfk.setObuId2(Transaction.getObuid()!=null?Transaction.getObuid():"0");
        zfk.setMessageId((double)etc.getMessageId());
        zfk.setTransType(Integer.valueOf(Transaction.getTransType()));
        zfk.setSpare2(Integer.valueOf(Transaction.getExVehicleId().split("_")[1]));
        zfk.setKeyVersion(Transaction.getAlgorithmIdentifier().doubleValue());

        //新增省域拆分
        if(Transaction.getMultiProvince()==1){
            zfk.setSplitNum(Transaction.getSplitProvince().size());
            String splitInfo="";
            for (int i = 0; i < Transaction.getSplitProvince().size(); i++) {
                splitInfo+=Transaction.getSplitProvince().get(i).getTollProvinceId()+":"+Transaction.getSplitProvince().get(i).getTollFee()+"|";
            }
            splitInfo=splitInfo.substring(0,splitInfo.length()-1);
            zfk.setSplitInfo(splitInfo);
        }

        return zfk;

    }

    /**
     * 插入mysql表
     * @param tblExitetctranslist
     * @throws Exception
     */
    @Transactional
    @DataSource("slave1")
    public void save(TblExitetctranslistEntity tblExitetctranslist) throws Exception{
        tblExitEtcTransDao.insert(tblExitetctranslist);
    }
}
